package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.CustomException;
import com.itheima.dto.DishDto;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.entity.DishFlavor;
import com.itheima.mapper.CategoryMapper;
import com.itheima.mapper.DishFlavorMapper;
import com.itheima.mapper.DishMapper;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜品管理 服务实现类
 * </p>
 *
 * @author Guoyh
 * @since 2022-08-21
 */
@Slf4j
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;


    @Override
    public Page selectByPageAndCondition(int page, int pageSize, String name) {
        Page pageInfo = new Page(page, pageSize);
        Page<DishDto> dishDtoPage = new Page();
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name).orderByDesc(Dish::getUpdateTime);

        dishMapper.selectPage(pageInfo, queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");

        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = new ArrayList<>();

        records.forEach(dish -> {
                    DishDto dishDto = new DishDto();
                    Long categoryId = dish.getCategoryId();
                    Category category = categoryMapper.selectById(categoryId);
                    String categoryName = category.getName();
                    dishDto.setCategoryName(categoryName);
                    BeanUtils.copyProperties(dish, dishDto);
                    list.add(dishDto);
                }
        );

        dishDtoPage.setRecords(list);
        return dishDtoPage;
    }

    @Transactional
    @Override
    public void saveDish(DishDto dishDto) {
        dishMapper.insert(dishDto);

        Long dishId = dishDto.getId();

        //菜品口味
        List<DishFlavor> flavors = dishDto.getFlavors();
        //stream流操作，把flavors中的每个DishFlavor对象的dishId传值
//        flavors.stream().map((item)->{
//            item.setDishId(dishId);
//            return item;
//        }).collect(Collectors.toList());

        flavors.forEach(dishFlavor -> dishFlavor.setDishId(dishId));
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public DishDto selectById(long id) {
        Dish dish = dishMapper.selectById(id);

        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, id);
        List<DishFlavor> dishFlavors = dishFlavorService.list(queryWrapper);

        DishDto dishDto = new DishDto();
        dishDto.setFlavors(dishFlavors);
        BeanUtils.copyProperties(dish, dishDto);
        return dishDto;
    }

    @Transactional
    @Override
    public void updateDish(DishDto dishDto) {
        //更新dish表基本信息
        dishMapper.updateById(dishDto);
        //更新dishflavor表信息
        /**
         * 先清理当前菜品对应的口味数据，再添加当前提交过来的口味数据
         */
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorService.remove(queryWrapper);

        Long dishId = dishDto.getId();
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors.forEach(dishFlavor -> dishFlavor.setDishId(dishId));
        dishFlavorService.saveBatch(flavors);
    }

    @Transactional
    @Override
    public void updateStatus(int flag, List<Long> ids) {
        for (int i = 0; i < ids.size(); i++) {
            Dish dish = dishMapper.selectById(ids.get(i));
            dish.setStatus(flag);
            LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Dish::getId, ids.get(i));
            this.update(dish,queryWrapper);
        }
    }

    @Transactional
    @Override
    public void removeWithFlavor(List<Long> ids) {
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Dish::getId, ids).eq(Dish::getStatus, 1);
        Integer count = dishMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new CustomException("菜品正在售卖中，不能删除");
        }
        dishMapper.deleteBatchIds(ids);

        LambdaQueryWrapper<DishFlavor> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.in(DishFlavor::getDishId, ids);
        dishFlavorMapper.delete(queryWrapper1);
    }


}
